<template>
  <a-row id="home" style="height: 95%;overflow: auto;">
    <a-col class="box-left">
      <div style="width: 200px;justify-content: center;display: flex;margin-top: 5px">
        <p>文章列表</p>
      </div>
      <a-tree
          style="width: 100%"
          :tree-data="treeData"
          @select="checkBtn"
      >
        <template #title="{ key: treeKey, title }">
          <a-dropdown :trigger="['contextmenu']">
            <span>{{ title }}</span>
            <template #overlay>
              <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                <a-menu-item key="delete">删除</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-tree>
      <a-pagination @change="changeBtn" simple v-model:current="totalThisPage" :total="total"/>
    </a-col>
    <a-col :span="20" :offset="4" style="border-left: 1px solid #ccc;padding-left: 10px;position: relative">
      <div
          style="height: 20px;display: flex;justify-content: right;position: absolute;left: -30px;top: 5px;cursor: pointer">
        <a-dropdown>
          <div>
            <PlusOutlined/>
          </div>
          <template #overlay>
            <a-menu @click="menuBtn">
              <a-menu-item style="line-height: 30px;height: 30px" key="1">
                <p>创建文章</p>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
      <div v-if="blogStatus"
           style="width: 100%;display: flex;justify-content: space-between;margin-top: 10px;margin-bottom: 10px">
        <div style="display: flex;width: 200px">
          <span style="width: 70px;line-height: 30px">标题：</span>
          <a-input v-model:value="thisBlogTitle" :disabled="titleStatus"></a-input>
        </div>
        <div>
          <a-button style="margin-right: 30px" :disabled="editBtnStatus" @click="editBtn">编辑</a-button>
          <a-button style="margin-right: 30px" :disabled="saveBtnStatus" @click="saveBtn">保存</a-button>
          <a-button style="margin-right: 30px" :disabled="releaseBtnStatus" @click="releaseBtn">发布</a-button>
        </div>
      </div>
      <v-md-preview-html v-if="editStatus === false" :html='blog_content' preview-class="vuepress-markdown-body"
                         style="overflow: auto;margin-top: 20px"></v-md-preview-html>
      <v-md-editor v-else v-model="editContent" height="calc(100vh - 110px)"></v-md-editor>
    </a-col>
  </a-row>
</template>

<script>
import {onMounted, ref} from "vue"
import {useRouter} from "vue-router"
import VueMarkdownEditor, {xss} from '@kangc/v-md-editor';
import {PlusOutlined} from '@ant-design/icons-vue'
import {message} from "ant-design-vue";

export default {
  name: 'Home',
  components: {
    PlusOutlined
  },
  setup() {
    const TurndownService = require('turndown').default
    let turndownService = new TurndownService()
    const router = useRouter()
    let treeData = ref([])
    let blog_content = ref('')
    let blog_content_list = []
    let editStatus = ref(false)
    let editContent = ref('')
    let thisBlog = 0
    let blogStatus = ref(false)
    let editBtnStatus = ref(false)
    let saveBtnStatus = ref(true)
    let thisBlogTitle = ref('')
    let titleStatus = ref(true)
    let releaseBtnStatus = ref(true)
    let total = ref('')
    let totalThisPage = ref(0)
    onMounted(() => {
      // 查询是否存在已设置的网站信息
      window.go.main.App.GetInitConfig().then(res => {
        if (res.code === 400) {
          message.warn("登录失败，请登录！")
          router.push("/login")
        } else {
          total.value = res.total
          totalThisPage.value = res.pages
          let list = res.msg
          for (let i = 0; i < list.length; i++) {
            let obj = {}
            if (list[i].title.rendered.length > 10) {
              obj.title = list[i].title.rendered.slice(0, 10) + "..."
            } else {
              obj.title = list[i].title.rendered
            }
            obj.key = i
            obj.articleId = list[i].id
            blog_content_list.push(list[i].content.rendered)
            treeData.value.push(obj)
          }
        }
      })
    })
    const checkBtn = (key, data) => {
      blogStatus.value = data.selected

      if (editStatus.value) {
        editStatus.value = false
        editBtnStatus.value = false
        saveBtnStatus.value = true
        titleStatus.value = true
        releaseBtnStatus.value = true
      }
      thisBlog = key[0]
      blog_content.value = blog_content_list[thisBlog]
      thisBlogTitle.value = treeData.value[thisBlog].title
    }

    const editBtn = () => {
      editBtnStatus.value = true
      saveBtnStatus.value = false
      editStatus.value = true
      titleStatus.value = false
      let markText = turndownService.turndown(blog_content.value)
      editContent.value = markText
    }
    const saveBtn = () => {
      editBtnStatus.value = false
      saveBtnStatus.value = true
      editStatus.value = false
      titleStatus.value = true
      let htmlCon = xss.process(VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(editContent.value));
      window.go.main.App.PutBlog(treeData.value[thisBlog].articleId, thisBlogTitle.value, htmlCon).then(() => {
        blog_content.value = htmlCon
        blog_content_list[thisBlog] = htmlCon
        treeData.value[thisBlog].title = thisBlogTitle.value
      })
    }
    const releaseBtn = () => {
      let htmlCon = xss.process(VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(editContent.value));
      window.go.main.App.ReleaseBlog(thisBlogTitle.value, htmlCon).then(() => {
        window.go.main.App.GetBlogPosts().then(res_get => {
          blog_content_list = []
          treeData.value = []
          if (res_get.code === 200) {
            let list = res_get.msg
            total.value = res_get.total
            totalThisPage.value = res_get.pages
            for (let i = 0; i < list.length; i++) {
              let obj = {}
              if (list[i].title.rendered.length > 10) {
                obj.title = list[i].title.rendered.slice(0, 10) + "..."
              } else {
                obj.title = list[i].title.rendered
              }
              obj.key = i
              obj.articleId = list[i].id
              blog_content_list.push(list[i].content.rendered)
              treeData.value.push(obj)
            }
            blog_content.value = blog_content_list[0]
            thisBlogTitle.value = treeData.value[0].title
            editBtnStatus.value = false
            saveBtnStatus.value = true
            releaseBtnStatus.value = true
            editStatus.value = false
            titleStatus.value = true
          } else {
            message.error("获取数据错误：", res_get.msg)
          }
        })

      })
    }
    const menuBtn = (e) => {
      switch (e.key) {
        case "1":
          editStatus.value = true;
          thisBlogTitle.value = '';
          editContent.value = '';
          saveBtnStatus.value = true;
          releaseBtnStatus.value = false;
          editBtnStatus.value = true;
          titleStatus.value = false;
          blogStatus.value = true
      }
    }
    const changeBtn = (page) => {
      console.log("page:", page)
      window.go.main.App.PostPages(page).then(res => {
        if (res.code === 400) {
          message.error("网络异常，请重试")
        } else {
          blog_content_list = []
          treeData.value = []
          total.value = res.total
          totalThisPage.value = parseInt(res.pages)
          let list = res.msg
          for (let i = 0; i < list.length; i++) {
            let obj = {}
            if (list[i].title.rendered.length > 10) {
              obj.title = list[i].title.rendered.slice(0, 10) + "..."
            } else {
              obj.title = list[i].title.rendered
            }
            obj.key = i
            obj.articleId = list[i].id
            blog_content_list.push(list[i].content.rendered)
            treeData.value.push(obj)
          }
        }
      })
    }
    // treeKey：文章id
    // menuKey：菜单选项id
    const onContextMenuClick = (treeKey, menuKey) => {
      if (menuKey === "delete") {
        window.go.main.App.DeleteArticle(treeData.value[treeKey].articleId).then(() => {
          message.success("删除成功")
          window.go.main.App.GetBlogPosts().then(res_get => {
            blog_content_list = []
            treeData.value = []
            if (res_get.code === 200) {
              let list = res_get.msg
              total.value = res_get.total
              totalThisPage.value = res_get.pages
              for (let i = 0; i < list.length; i++) {
                let obj = {}
                if (list[i].title.rendered.length > 10) {
                  obj.title = list[i].title.rendered.slice(0, 10) + "..."
                } else {
                  obj.title = list[i].title.rendered
                }
                obj.key = i
                obj.articleId = list[i].id
                blog_content_list.push(list[i].content.rendered)
                treeData.value.push(obj)
              }
              blog_content.value = blog_content_list[0]
              thisBlogTitle.value = treeData.value[0].title
              editBtnStatus.value = false
              saveBtnStatus.value = true
              releaseBtnStatus.value = true
              editStatus.value = false
              titleStatus.value = true
            } else {
              message.error("获取数据错误：", res_get.msg)
            }
          })
        })
      }
    };
    return {
      treeData,
      blog_content,
      checkBtn,
      editBtn,
      saveBtn,
      editStatus,
      editContent,
      blogStatus,
      editBtnStatus,
      saveBtnStatus,
      thisBlogTitle,
      menuBtn,
      titleStatus,
      releaseBtnStatus,
      releaseBtn,
      totalThisPage,
      total,
      changeBtn,
      onContextMenuClick
    }
  }
}
</script>

<style scoped>
#home::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

#home::-webkit-scrollbar-track {
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.06);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.08);
}

#home::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: rgba(0, 0, 0, 0.12);
  -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.2);
}

.box-left {
  position: absolute;
  top: 25px;
  moz-user-select: -moz-none;
  -moz-user-select: none;
  -o-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>
